package com.egao.common.module.system.transfer;

import com.egao.common.core.web.JsonResult;
import com.egao.common.module.company.entity.*;
import com.egao.common.module.company.service.*;
import com.egao.common.module.push.constants.PushConstants;
import com.egao.common.module.push.entity.PushMsg;
import com.egao.common.module.push.mapper.PushMsgMapper;
import com.egao.common.module.push.service.PushMsgService;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 单位数据导入
 * @author: dl
 */
@RestController
@Slf4j
public class PushMsgDataController {

    @Value("${old.datasource.jyurl}")
    private String url;

    @Value("${old.datasource.username}")
    private String userName;

    @Value("${old.datasource.password}")
    private String password;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private PushMsgMapper pushMsgMapper;

    @Autowired
    private StudentService studentService;

    @Autowired
    private RecruitService recruitService;

    @Autowired
    private PreachService preachService;

    @Autowired
    private PositionService positionService;

    public JsonResult transfer(@RequestParam(name="limit",defaultValue="5000") Integer limit) {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        List<Company> companyList = getCompanyList();
        List<Preach> preachList = getPreachList();
        List<Recruit> recruitList = getRecruitList();
        List<Student> studentList = getStudentList();
        List<Position> positionList = getPositionList();
        // 开始时间
        long startLong = System.currentTimeMillis();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, userName, password);
            st = conn.createStatement();
            String countSQL = "SELECT COUNT(1) FROM push_msg push_msg WHERE company_flag = '1' AND admin_flag = '1' ";
            rs = st.executeQuery(countSQL);
            int total = 0;
            if (rs.next()) {
                total = rs.getInt(1);
            }
            if (total == 0) {
                return JsonResult.error("没有数据");
            }
            int size = total / limit;
            if (total % limit != 0) {
                size ++;
            }
            for (int k = 0; k < size; k++) {
                List<PushMsg> pushMsgList = new ArrayList<>();
                int number = k * limit;
                if (k == size - 1) {
                    limit = total - number;
                }
                String sql = "SELECT " +
                        "  id " +
                        ", company_flag " +
                        ", admin_flag " +
                        ", student_id " +
                        ", type " +
                        ", matching " +
                        ", page_id " +
                        ", company_id " +
                        ", title " +
                        ", page_date " +
                        ", push_date " +
                        ", push_content " +
                        ", position_matching " +
                        ", read_flag " +
                        ", read_date " +
                        ", resume_flag " +
                        ", resume_date " +
                        ", resume_file " +
                        ", create_date " +
                        ", update_date " +
                        ", del_flag " +
                        " FROM push_msg WHERE company_flag = '1' AND admin_flag = '1' limit " + number + ", " + limit;
                st = conn.createStatement();
                rs = st.executeQuery(sql);
                log.info("总数：{}", rs.getRow());
                int i = 0;
                while (rs.next()) {
                    String oldId = rs.getString("id");
                    String companyFlag = rs.getString("company_flag");
                    String adminFlag = rs.getString("admin_flag");
                    String studentId = rs.getString("student_id");
                    String type = rs.getString("type");
                    String matching = rs.getString("matching");
                    String page_id = rs.getString("page_id");
                    String companyid = rs.getString("company_id");
                    String title = rs.getString("title");

                    Date pageDate = rs.getTimestamp("page_date") != null ? new Date(rs.getTimestamp("page_date").getTime()) : null;
                    Date pushDate = rs.getTimestamp("push_date") != null ? new Date(rs.getTimestamp("push_date").getTime()) : null;
                    String push_content = rs.getString("push_content");
                    String position_matching = rs.getString("position_matching");
                    String readFlag = rs.getString("read_flag");
                    Date readDate = rs.getTimestamp("read_date") != null ? new Date(rs.getTimestamp("read_date").getTime()) : null;
                    String resumeFlag = rs.getString("resume_flag");
                    Date resumeDate = rs.getTimestamp("resume_date") != null ? new Date(rs.getTimestamp("resume_date").getTime()) : null;
                    String resumeFile = rs.getString("resume_file");

                    String del_flag = rs.getString("del_flag");
                    PushMsg pushMsg = new PushMsg();

                    if (rs.getTimestamp("create_date") != null) {
                        Date createDate = new Date(rs.getTimestamp("create_date").getTime());
                        pushMsg.setCreateTime(createDate);
                    }
                    if (rs.getTimestamp("update_date") != null) {
                        Date updateDate = new Date(rs.getTimestamp("update_date").getTime());
                        pushMsg.setUpdateTime(updateDate);
                    }

                    pushMsg.setCompanyFlag(PushConstants.YES.equals(companyFlag) ? PushConstants.NO : PushConstants.YES);
                    pushMsg.setAdminFlag(PushConstants.YES.equals(adminFlag) ?  PushConstants.NO : PushConstants.YES);

                    if (readFlag != null) {
                        readFlag = PushConstants.YES.equals(readFlag) ?  PushConstants.NO : PushConstants.YES;
                    }
                    pushMsg.setReadFlag(readFlag);
                    if (readDate != null) {
                        pushMsg.setReadDate(readDate);
                    }
                    if (resumeFlag != null) {
                        resumeFlag = PushConstants.YES.equals(resumeFlag) ?  PushConstants.NO : PushConstants.YES;
                    }
                    pushMsg.setResumeFlag(resumeFlag);
                    if (resumeDate != null) {
                        pushMsg.setResumeDate(resumeDate);
                    }
                    if (pageDate != null) {
                        pushMsg.setBusinessDate(pageDate);
                    }
                    if (pushDate != null) {
                        pushMsg.setPushDate(pushDate);
                    }
                    pushMsg.setPushType(PushConstants.YES);
                    pushMsg.setResumeFile(resumeFile);

                    pushMsg.setOldId(oldId);
                    pushMsg.setTitle(title);

                    pushMsg.setType(type);
                    pushMsg.setMatching(matching);

                    pushMsg.setDeleted("0".equals(del_flag) ? 0 : 1);
                    pushMsg.setCid(companyid);
                    pushMsg.setBid(page_id);

                    if (companyid != null) {
                        Company company = getCompanyId(companyList, companyid);
                        if (company != null) {
                            pushMsg.setCompanyId(company.getId());
                        } else {
                            pushMsg.setSuccessFlag(PushConstants.SUCCESS_FLAG_COMPANY);
                        }
                    }

                    Student student = getStudent(studentList, studentId);
                    if (student != null) {
                        pushMsg.setStudentId(student.getId());
                        pushMsg.setXh(student.getXh());
                        pushMsg.setYearId(student.getYearId());
                        String pushContent = getPushContent(push_content, student.getId());
                        pushMsg.setPushContent(pushContent);
                        if (PushConstants.NO.equals(pushContent)) {
                            pushMsg.setSuccessFlag(PushConstants.SUCCESS_FLAG_PUSH_CONTENT);
                        }
                    } else {
                        pushMsg.setSuccessFlag(PushConstants.SUCCESS_FLAG_STUDENT);
                    }

                    // 招聘信息
                    if ("1".equals(type)) {
                        Recruit recruit = getRecruit(recruitList, page_id);
                        if (recruit != null) {
                            pushMsg.setBusinessId(recruit.getId());
                        } else {
                            pushMsg.setSuccessFlag(PushConstants.SUCCESS_FLAG_RECRUIT);
                        }
                    } else if ("2".equals(type)) {
                        Preach preach = getPreach(preachList, page_id);
                        if (preach != null) {
                            pushMsg.setBusinessId(preach.getId());
                        } else {
                            pushMsg.setSuccessFlag(PushConstants.SUCCESS_FLAG_PREACH);
                        }
                    } else {
                        pushMsg.setSuccessFlag(PushConstants.SUCCESS_FLAG_TYPE);
                    }

                    if (pushMsg.getSuccessFlag() == null) {
                        pushMsg.setSuccessFlag(PushConstants.YES);
                    }

                    if (position_matching != null) {
                        String[] arr = position_matching.split("\\|");
                        StringBuilder sr = new StringBuilder();
                        for (int a = 0; a < arr.length; a++) {
                            String s = arr[a];
                            int start = s.indexOf(",");
                            if (start < 0) {
                                pushMsg.setSuccessFlag(PushConstants.SUCCESS_FLAG_POSITION);
                                break;
                            }
                            String oldPositionId = s.substring(0, start);
                            Position position = getPosition(positionList, oldPositionId);
                            if (position == null) {
                                pushMsg.setSuccessFlag(PushConstants.SUCCESS_FLAG_POSITION);
                                break;
                            }
                            sr.append(position.getId()).append(s.substring(start)).append("|");
                        }
                        position_matching = sr.toString();
                    }
                    pushMsg.setPositionMatching(position_matching);
                    i++;
                    pushMsgList.add(pushMsg);

                }
                pushMsgMapper.batchImport(pushMsgList);
                pushMsgList.clear();
                log.info("推送信息：{} 次", k);
            }
            // 结束时间
            long endLong = System.currentTimeMillis();
            long seconds = (endLong - startLong) / 1000 / 60;
            log.info("完成时间 : {} 分", seconds);
            return JsonResult.ok(String.format("完成时间 : %s 分", seconds));
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                st.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return JsonResult.error("失败");
    }


    /**
     * 查询所有单位信息
     *
     * @return
     */
    private List<Company> getCompanyList() {
        return companyService.list();
    }

    /**
     * 查询所有学生信息
     *
     * @return
     */
    private List<Student> getStudentList() {
        return studentService.list();
    }

    /**
     * 查询所有招聘信息
     *
     * @return
     */
    private List<Recruit> getRecruitList() {
        return recruitService.list();
    }

    private List<Preach> getPreachList() {
        return preachService.list();
    }

    /**
     * 查询单位原始
     *
     * @return
     */
    private Company getCompanyId(List<Company> companyList, String oldId) {
        for (Company company : companyList) {
            if (oldId.equals(company.getOldId())) {
                return company;
            }
        }
        return null;
    }
    /**
     * 查询学生原始
     *
     * @return
     */
    private Student getStudent(List<Student> studentList, String studentId) {
        for (Student student : studentList) {
            if (studentId.equals(student.getOldId())) {
                return student;
            }
        }
        return null;
    }
    /**
     * 查询宣讲会原始
     *
     * @return
     */
    private Preach getPreach(List<Preach> preachList, String preachId) {
        for (Preach preach : preachList) {
            if (preachId.equals(preach.getOldId())) {
                return preach;
            }
        }
        return null;
    }
    /**
     * 查询招聘信息原始
     *
     * @return
     */
    private Recruit getRecruit(List<Recruit> recruitList, String recruitId) {
        for (Recruit recruit : recruitList) {
            if (recruitId.equals(recruit.getOldId())) {
                return recruit;
            }
        }
        return null;
    }
    /**
     * 更换学生编号
     *
     * @return
     */
    private String getPushContent(String pushContent, Integer studentId) {
        if (pushContent != null) {
            int start = pushContent.indexOf("id=");
            int end = pushContent.indexOf("*t");
            if (start < 0 || end < 0) {
                return PushConstants.NO;
            }
            return pushContent.substring(0, start + 3) + studentId + pushContent.substring(end);
        }
        return null;
    }

    private List<Position> getPositionList() {
        return positionService.list();
    }
    /**
     * 查询职位
     *
     * @return
     */
    private Position getPosition(List<Position> positionList, String positionId) {
        for (Position position : positionList) {
            if (positionId.equals(position.getOldId())) {
                return position;
            }
        }
        return null;
    }
}
